import sys
import getopt
import random
import os
import pylab as plt

from placefriends_utilities import *
from placefriends_allowed import *
from params import *

## Symbols 
#symbols = ['--','-.',':','.',',','+','^','v','<','>','s','o','x','D','d','1','2','3','4','h','H','p']
#symbols = ['-','--','-.',':','.',',','+','1','2','3','4','x','s','o','^','v','p','h','H','<','>','D','d']
## Symbols + line
#ps = [',','.','x','^','v','<','>','s','+','o','D','d','1','2','3','4','h','H','p']
#lps = [k+'-' for k in ps]

RATIO=1.25
fig_width_pt = 246.0  # Get this from LaTeX using \showthe\columnwidth
inches_per_pt = 1.0/72.27               # Convert pt to inch
fig_width = fig_width_pt*inches_per_pt  # width in inches
fig_height = fig_width*RATIO#*golden_mean      # height in inches
fig_size =  [fig_width,fig_height]
params = {'figure.figsize': fig_size}
plt.rcParams.update(params)
#alternative size for more space on the left side
FIG_AXES_SQ = [0.15,0.125,0.95-0.15,0.125+0.65/RATIO]

DIR = os.path.join(WORKDIR, 'gowalla', 'final', 'kdd_test')
def main(argv):
    try:
        opts,args = getopt.getopt(argv,'mf',
                ['month=','flag='])
    except getopt.GetoptError:
        err_msg("Option format error")
        sys.exit()

    month = None
    flag = None
    for opt,arg in opts:
        if opt  == '--month':
            month = arg
        if opt == '--flag':
            flag = arg

    if not month:
        err_msg("Missing month value")
        sys.exit()
    if not flag:
        err_msg("Missing flag value")
        sys.exit()

    filename = os.path.join(DIR,'graphs_%s_%s.dat'%(month,flag))
    total_plots=[]
    data = []
    for line in open(filename):
        d = eval(line)
        name, roc, dev =d[:3]
        if not name in lbls:
            continue
        xrf,yrf = d[3:5]
        xroc,yroc = d[-2:]
        if flag == 'PLACE':
            yroc = map(lambda x: min(1.0,x/0.96),yroc)
        total_plots.append((xroc,yroc,name))
        #total_plots.append((xrf,yrf,name))
        data.append((roc,dev,lbls[name]))
        if name.startswith('AAPlaceOverlapScoreComputer'):
            x1,y1 = xroc,yroc
            r1,d1 = roc,dev
        if name.startswith('MinEntropyScoreComputer'):
            x2,y2 = xroc,yroc
            r2,d2 = roc,dev

    if flag != 'SOCIAL':
        x = []
        for a,b,c in zip(x1,x2,y1):
            x.append(0.5*(a+b))
        total_plots.append((x,y1,'MinCheckinScoreComputer'))
        data.append((0.5*(r1+r2),0.5*(d1+d2),lbls['MinCheckinScoreComputer']))

    data.sort()
    data.reverse()
    print ''
    print flag
    for roc,dev,name in data:
        print 'Feature %s with ROC %f +/- %f'%(name, roc, dev)
    plt.figure()#figsize=(7,7))
    plt.clf()
    plt.axes(FIG_AXES_SQ)
    legs = []
    for x,y,n in total_plots:
        #s = pf_markers[n]
        s = pf_colormarkers[n]
        plt.plot(x,y,'%s'%(s),markersize=4)
        legs.append(lbls[n])
    plt.legend(legs,#loc='lower right',
            ncol=3,numpoints=1,
            bbox_to_anchor=(0., 1.02, 1., .102), loc=3,
            mode="expand", borderaxespad=0.)
    #plt.plot([0,1],[0,1],'k-')
    plt.xlabel('False Positive Rate')
    plt.ylabel('True Positive Rate')
    plt.grid(True)
    plt.axis([0,1,0,1])
    plt.savefig('total_roc_%s_%s.pdf'%(month,flag))
    plt.close()

if __name__ == '__main__':
    #for month in [5,6,7]:
    for month in [7]:
        for flag in ['SOCIAL','PLACE','BOTH']:
            args = '--flag=%s --month=%d'%(flag,month)
            main(args.split())
            #main(sys.argv[1:])
